package jmind.core.spring;

import com.alibaba.fastjson.JSONObject;
import jmind.base.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.HtmlUtils;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URL;

/**
 * 抽象controller
 * @author wbxie
 * 2013-10-29
 */
public abstract class AbstractController {

    protected final Logger logger = LoggerFactory.getLogger(getClass());
    public static final String JSON_SUCCESS = "{\"code\":0,\"msg\":\"ok\"}";
    public static final String JSON_FAIL = "{\"code\":1,\"msg\":\"参数错误！\"}";
    public static final String REDIRECT = "redirect:";

    /**
     * 文件保存
     * @param myfile
     * @param file
     * @return
     */
    protected File transferFile(MultipartFile myfile, String file) {
        File dest = new File(file);
        FileUtil.makeDir(dest.getParentFile());
        try {
            myfile.transferTo(dest);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // dest.getAbsolutePath()
        return dest;
    }

    //   see SpringBinder
    //    @InitBinder
    //    public void initBinder(ServletRequestDataBinder binder) {
    //

    //        /**
    //         * 自动转换日期类型的字段格式
    //         */
    //          StringEscapeEditor see = new StringEscapeEditor(true, false);
    //        binder.registerCustomEditor(Date.class, new org.springframework.beans.propertyeditors.CustomDateEditor(
    //                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
    //        binder.registerCustomEditor(Date.class, new org.springframework.beans.propertyeditors.CustomDateEditor(
    //                new SimpleDateFormat("yyyy-MM-dd"), true));
    //        /**
    //         * 防止XSS攻击
    //         */
    //        binder.registerCustomEditor(String.class, see);
    //    }

    protected String getRefer(HttpServletRequest request) {
        return request.getHeader("Referer");
    }

//    /**
//     * 构造page对象， 总页数默认
//     * @param request
//     * @return
//     */
//    public static <E> Page<E> newPage(HttpServletRequest request) {
//        Page<E> page = new Page<E>();
//        int curpage = RequestUtil.getParamInt(request, "page", 1);
//        if (curpage < 1)
//            curpage = 1;
//        page.setPage(curpage);
//        page.setRows(RequestUtil.getParamInt(request, "rows", 20));
//        page.setUri(request.getRequestURI());
//        page.setQuery(RequestUtil.getParameterMap(request));
//        page.setCount(RequestUtil.getParamInt(request, "count", 0));
//        request.setAttribute("pages", page);
//        return page;
//
//    }

    /**
     * 根据url 取host
     * @param url
     * @return
     */
    protected String getHost(String url) {
        if (!DataUtil.isEmpty(url)) {
            try {
                URL domain = new URL(url);
                String host = domain.getHost();
                return host;
            } catch (Exception e) {
            }
        }
        return DataUtil.EMPTY;
    }

    /**
     * ip
     * @param request
     * @return
     */
    protected String getIp(HttpServletRequest request) {
        return IpUtil.getIp(request);
    }

    /* ------------------------- ajax操作jsonp支持 ------------------------- */

    protected String wrapJsonCallback(ServletRequest request, String json) {
        String callback = request.getParameter("callback");
        return DataUtil.isEmpty(callback) ? json : String.format("%s(%s)", HtmlUtils.htmlEscape(callback), json);
    }

    protected void logErr(HttpServletRequest request) {
        logger.error("request: {}", RequestUtil.getURL(request));
        // request.getHeader("Accept")
        logger.error(":UA=" + request.getHeader("User-Agent") + "[refer=" + this.getRefer(request) + "][ajax="
                + request.getHeader("X-Requested-With"));

    }

    /* ------------------------- 异常处理 ------------------------- */

    @ExceptionHandler(Throwable.class)
    public void handleException(Throwable e, HttpServletRequest request, HttpServletResponse response) {
        logErr(request);
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding(GlobalConstants.UTF8);
        JSONObject s = new JSONObject();
        s.put("code", 9999);
        s.put("msg", e.getMessage());
        try {
            request.setCharacterEncoding(GlobalConstants.UTF8);
            response.getWriter().write(s.toJSONString());
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    protected boolean isAjax(HttpServletRequest request) {
        return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
    }

}
